<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Db;
use app\common\model\ViperType as ViperType_Model;
use app\common\model\Goods;
use app\common\model\Project;
use app\common\model\MonthCardTemplate;
use app\common\model\NumberCardTemplate;
use app\common\model\RechargeTemplate;
use app\common\model\ViperPackageItem;

class ViperType extends Admin
{

    /**
     * 套餐列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index(){
        // 读取数据
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = ViperType_Model::where($map)->order($order)->paginate();
        // 分页数据
        $page = $data_list->render();

        $btn_add = [
            'title' => '新增会员类型',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];

        $btn_edit = [
            'title' => '修改会员类型',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-info btn-sm',
            'href' => url('edit',['id'=>"__id__"]),
        ];

        $btn_item = [
            'title' => '添加包含项目或者商品',
            'icon' => 'fa fa-fw fa-scribd',
            'class' => 'btn btn-info btn-sm',
            'href' => url('addItem',['id'=>"__id__"]),
        ];

        $btn_item_list = [
            'title' => '查看包含的项目或者商品列表',
            'icon' => 'fa fa-fw fa-sitemap',
            'class' => 'btn btn-info btn-sm',
            'href' => url('itemLists',['id'=>"__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('name', '名称', 'text')
            ->addColumn('expire_month', '有效期', 'text')
            ->addColumn('silence_day', '沉默时间', 'text')
            ->addColumn('rule_name', '积分规则', 'text')
            ->addColumn('use_number_warning', '当天消费次数预警', 'text')
            ->addColumn('birthday_how_long', '生日提醒', 'text')
            ->addColumn('is_across_store_recharge', '跨店充值', 'status','',[1=>'允许:success',0=>'不允许:danger'])
            ->addColumn('is_across_store_give', '跨店赠送金额', 'status','',[1=>'允许:success',0=>'不允许:danger'])
            ->addColumn('is_discount', '打折', 'status','',[1=>'打折:success',0=>'禁止打折:danger'])
            ->addColumn('right_button', '操作', 'btn')
            ->setTableName('qt_viper_type')// 指定数据表名
            ->addTopButton('add', $btn_add)// 添加顶部按钮
            ->addRightButton('edit', $btn_edit)// 添加顶部按钮
            ->addRightButton('item', $btn_item)// 添加顶部按钮
            ->addRightButton('lists', $btn_item_list)// 添加顶部按钮
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('套餐列表')
            ->setRowList($data_list)// 设置表格数据
            ->setPages($page)// 设置分页数据
            ->fetch();
    }

    /**
     * 添加套餐
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            $info = ViperType_Model::get(['name'=>$data['name']]);

            if ($info)$this->error('会员卡类型名称已经存在');


            Db::startTrans();

            try{
                $arr['type']=$data['type'];
                $arr['name']=$data['name'];
                $arr['expire_month']=$data['expire_month'];
                $arr['rule']=$data['rule'];
                $arr['amount']=$data['amount'];
                $arr['integral_1']=$data['integral_1'];
                $arr['number']=$data['number'];
                $arr['integral_2']=$data['integral_2'];
                $arr['hz']=$data['month_hz'];
                $arr['use_number_warning']=$data['use_number_warning'];
                $arr['birthday_how_long']=$data['birthday_how_long'];
                $arr['is_across_store_recharge']=intval($data['is_across_store_recharge']);
                $arr['is_across_store_give']=intval($data['is_across_store_give']);
                $arr['is_discount']=intval($data['is_discount']);
                $arr['recharge_id']='';
                $arr['number_card_id']='';
                $arr['month_card_id']='';

                switch ($data['type'])
                {
                        case 1:
                            $template = RechargeTemplate::create([
                                'name'=>$data['recharge_name'],
                                'amount'=>$data['recharge_amount'],
                                'rate'=>'recharge_rate']);
                            $arr['recharge_id']=$template['id'];

                            break;
                        case 2;
                            $template =NumberCardTemplate::create([
                                'name'=>$data['number_name'],
                                'amount'=>$data['number_amount'],
                                'number_rate'=>$data['number_rate'],
                                'project_ids'=>count($data['project_id'])?implode(',',$data['project_id']):'',
                            ]);

                            $arr['number_card_id']=$template['id'];
                        break;
                        case 3;
                            $template = MonthCardTemplate::create([
                                'name'=>$data['month_name'],
                                'amount'=>intval($data['month_amount']),
                                'rate'=>$data['month_rate'],
                                'expire'=>$data['month_expire'],
                                'hz'=>$data['month_hz'],
                                'type'=>$data['month_type'],
                                'good_ids'=>count($data['good_id'])>0?implode(',',$data['good_id']):'',
                                'project_ids'=>count($data['project_id'])?implode(',',$data['project_id']):'',
                            ]);
                            $arr['month_card_id']=$template['id'];

                            break;
                }


                ViperType_Model::create($arr);


                Db::commit();


            }catch (\Exception $e){
                Db::rollback();
                halt($e->getMessage());
            }

            $this->success('新增成功', 'index');

        } else {
            $project_list = Project::column('id,name');
            $goods_list = Goods::column('id,name');
            return ZBuilder::make('form')
                ->addFormItems([
                    ['text', 'name','','','',['类型名称:']],
                    ['text', 'expire_month','','','',['会员有效期:'],'月'],
                    ['text', 'silence','','','',['会员沉默:','天后消失']],
                    ['radio', 'rule','积分规则','',[1=>'按照消费金额',2=>'按照消费次数']],

                    ['text', 'amount', '','','',['积分规则按照消费金额，消费的金额:']],
                    ['text', 'integral_1', '','','',['积分规则按照消费金额，赠送的积分:']],
                    ['text', 'number', '','','',['积分规则按照消费次数，消费次数:']],
                    ['text', 'integral_2', '','','',['积分规则按照消费次数，赠送的积分:']],
                    ['text', 'use_number_warning', '','','',['会员消费','次预警']],
                    ['text', 'birthday_how_long', '','','',['距离生日:','天和生日当日提醒']],
                    ['radio','is_across_store_recharge','跨店充值:','',[1=>'是',0=>'否']],
                    ['radio','is_across_store_give','跨店赠送:','',[1=>'是',0=>'否']],
                    ['radio','is_discount','打折:','',[1=>'是',0=>'否']],
                    ['radio','type','开卡类型:','',[1=>'充值',2=>'次卡',3=>'月卡/年卡']],
                    ['text','recharge_name','','','',['模版名称:']],
                    ['text','recharge_amount','','','',['充值金额:']],
                    ['text','recharge_rate','','','',['提成:']],
                    ['text','recharge_integral','','','',['积分:']],
                    ['text','number_name','','','',['模版名称:']],
                    ['text','number_amount','','','',['售价:']],
                    ['text','number_rate','','','',['提成:']],
                    ['text','month_name','','','',['模版名称:']],
                    ['text','month_amount','','','',['售价:']],
                    ['text','month_rate','','','',['售价:']],
                    ['text','month_expire','','','',['时效:','天']],
                    ['text','month_hz','','','',['使用频率:','次']],
                    ['radio','month_type','类型:','',[1=>'次/天',2=>'次/月',3=>'3=次/年']],
                    ['select','project_id','包含项目:','',$project_list,'','multiple'],
                    ['select','good_id','包含的商品:','',$goods_list,'','multiple'],

                ])
                ->setTrigger('rule', 1, 'amount,integral_1')
                ->setTrigger('rule', 2, 'number,integral_2')
                ->setTrigger('type', '1', 'recharge_name,recharge_amount,recharge_rate,recharge_integral')
                ->setTrigger('type', '2', 'number_name,number_amount,number_rate')
                ->setTrigger('type', '3', 'month_name,month_amount,month_expire,month_hz,month_type,goods_id')
                ->setTrigger('type', '2,3', 'project_id')
                ->setPageTitle('添加套餐')
                ->fetch();
        }
    }


    /**
     * 编辑套餐
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            Db::startTrans();

            try{
                $arr['type']=$data['type'];
                $arr['name']=$data['name'];
                $arr['expire_month']=$data['expire_month'];
                $arr['rule']=$data['rule'];
                $arr['amount']=$data['amount'];
                $arr['integral_1']=$data['integral_1'];
                $arr['number']=$data['number'];
                $arr['integral_2']=$data['integral_2'];
                $arr['hz']=$data['month_hz'];
                $arr['use_number_warning']=$data['use_number_warning'];
                $arr['birthday_how_long']=$data['birthday_how_long'];
                $arr['is_across_store_recharge']=$data['is_across_store_recharge'];
                $arr['is_across_store_give']=$data['is_across_store_give'];
                $arr['is_discount']=$data['is_discount'];
                $arr['recharge_id']='';
                $arr['number_card_id']='';
                $arr['month_card_id']='';

                switch ($data['type'])
                {
                    case 1:
                        $template = RechargeTemplate::create([
                            'name'=>$data['recharge_name'],
                            'amount'=>$data['recharge_amount'],
                            'rate'=>'recharge_rate']);
                        $arr['recharge_id']=$template['id'];

                        break;
                    case 2;
                        $template =NumberCardTemplate::create([
                            'name'=>$data['number_name'],
                            'amount'=>$data['number_amount'],
                            'number_rate'=>$data['number_rate'],
                            'project_ids'=>count($data['project_id'])>0?implode(',',$data['project_id']):'',
                        ]);

                        $arr['number_card_id']=$template['id'];
                        break;
                    case 3;
                        $template = MonthCardTemplate::create([
                            'name'=>$data['month_name'],
                            'amount'=>intval($data['month_amount']),
                            'rate'=>$data['month_rate'],
                            'expire'=>$data['month_expire'],
                            'hz'=>$data['month_hz'],
                            'type'=>$data['month_type'],
                            'good_ids'=>count($data['good_id'])>0?implode(',',$data['good_id']):'',
                            'project_ids'=>count($data['project_id'])>0?implode(',',$data['project_id']):'',
                        ]);
                        $arr['month_card_id']=$template['id'];

                        break;
                }


                ViperType_Model::create($arr);


                Db::commit();


            }catch (\Exception $e){
                Db::rollback();
                halt($e->getMessage());
            }
        } else {
            $info = ViperType_Model::get($id);
            $project_list = Project::column('id,name');
            $goods_list = Goods::column('id,name');
            if (!empty($info['recharge_id']))
            {
                $recharge_template = RechargeTemplate::get($info['recharge_id']);
            }

            if (!empty($info['number_card_id']))
            {
                $number_template = NumberCardTemplate::get($info['number_card_id']);
            }

            if (!empty($info['month_card_id']))
            {
                $month_template = MonthCardTemplate::get($info['month_card_id']);
            }
            return ZBuilder::make('form')
                ->addFormItems([
                    ['text', 'name','','','',['类型名称:']],
                    ['text', 'expire_month','','','',['会员有效期:'],'月'],
                    ['text', 'silence','','','',['会员沉默:','天后消失']],
                    ['radio', 'rule','积分规则','',[1=>'按照消费金额',2=>'按照消费次数']],
                    ['text', 'amount', '','','',['积分规则按照消费金额，消费的金额:']],
                    ['text', 'integral_1', '','','',['积分规则按照消费金额，赠送的积分:']],
                    ['text', 'number', '','','',['积分规则按照消费次数，消费次数:']],
                    ['text', 'integral_2', '','','',['积分规则按照消费次数，赠送的积分:']],
                    ['text', 'use_number_warning', '','','',['会员消费','次预警']],
                    ['text', 'birthday_how_long', '','','',['距离生日:','天和生日当日提醒']],
                    ['radio','is_across_store_recharge','跨店充值:','',[1=>'是',0=>'否']],
                    ['radio','is_across_store_give','跨店赠送:','',[1=>'是',0=>'否']],
                    ['radio','is_discount','打折:','',[1=>'是',0=>'否']],
                    ['radio','type','开卡类型:','',[1=>'充值',2=>'次卡',3=>'月卡/年卡']],
                    ['text','recharge_name','','',!empty($recharge_template)?$recharge_template['name']:'',['模版名称:']],
                    ['text','recharge_amount','','',!empty($recharge_template)?$recharge_template['amount']:'',['充值金额:']],
                    ['text','recharge_rate','','',!empty($recharge_template)?$recharge_template['rate']:'',['提成:']],
                    ['text','recharge_integral','','',!empty($recharge_template)?$recharge_template['integral']:'',['积分:']],
                    ['text','number_name','','',!empty($number_template)?$number_template['name']:'',['模版名称:']],
                    ['text','number_amount','','',!empty($number_template)?$number_template['amount']:'',['售价:']],
                    ['text','number_rate','','',!empty($number_template)?$number_template['rate']:'',['提成:']],
                    ['text','month_name','','',!empty($month_template)?$month_template['name']:'',['模版名称:']],
                    ['text','month_amount','','',!empty($month_template)?$month_template['amount']:'',['售价:']],
                    ['text','month_rate','','',!empty($month_template)?$month_template['rate']:'',['提成:']],
                    ['text','month_expire','','',!empty($month_template)?$month_template['expire']:'',['时效:','天']],
                    ['text','month_hz','','',!empty($month_template)?$month_template['hz']:'',['使用频率:','次']],
                    ['radio','month_type','类型:','',[1=>'次/天',2=>'次/月',3=>'3=次/年'],!empty($month_template)?$month_template['type']:null],
                    ['select','project_id','包含项目:','',$project_list,!empty($month_template)?$month_template['goods_id']:'','multiple'],
                    ['select','good_id','包含的商品:','',$goods_list,!empty($month_template)?$month_template['project_id']:null,'multiple'],
                ])
                ->setTrigger('rule', 1, 'amount,integral_1')
                ->setTrigger('rule', 2, 'number,integral_2')
                ->setTrigger('type', '1', 'recharge_name,recharge_amount,recharge_rate,recharge_integral')
                ->setTrigger('type', '2', 'number_name,number_amount,number_rate')
                ->setTrigger('type', '3', 'month_name,month_amount,month_expire,month_hz,month_type,goods_id')
                ->setTrigger('type', '2,3', 'project_id')
                ->setFormData($info)
                ->setPageTitle('添加套餐')
                ->fetch();
        }
    }

    /**
     * 添加套餐关联的商品或者项目
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addItem($id=null)
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post();

            $arr = [];

            if ($data['type']=='goods')
            {
                $goods_info = Goods::get(['id'=>$data['goods_id']]);

                $arr['name'] = $goods_info['name'];
                $arr['price'] = $goods_info['price'];
            }elseif ($data['type']=='project')
            {
                $project_info = Goods::get(['id'=>$data['project_id']]);

                $arr['name'] = $project_info['name'];
                $arr['price'] = $project_info['price'];

            }

            $arr['package_id'] = $data['package_id'];
            $arr['item_id'] = $data['type']=="goods"?$data['goods_id']:$data['project_id'];
            $arr['item_type'] = $data['type'];
            $arr['number'] = $data['number'];

            $item_info = ViperPackageItem::get(['item_id'=>$arr['item_id'],'item_type'=>$arr['item_type']]);

            if ($item_info)
            {
                $item_info->number = $item_info['number']+$arr['number'];

                $result = $item_info->save();
            }else{
                $result = ViperPackageItem::create($arr);
            }

            $result?$this->success('操作成功','index'):$this->error('操作失败');

        }

        $goods_list = Goods::column('id,name');

        $project_list = Goods::column('id,name');

        return ZBuilder::make('form')
            ->addHidden('package_id',$id)
            ->addRadio('type','请选择项目:','',['goods'=>'商品','project'=>'项目'])
            ->addSelect('goods_id', '请选择商品', '', $goods_list)
            ->addSelect('project_id', '请选择项目', '', $project_list)
            ->setTrigger('type', 'goods', 'goods_id')
            ->setTrigger('type', 'project', 'project_id')
            ->addNumber('number', '数量', '', '', '0', '100')
            ->setFormData()
            ->setPageTitle('编辑项目')
            ->fetch();
    }

    /**
     * 包含的项目或者商品列表
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function itemLists($id)
    {

        $list = ViperPackageItem::where('package_id',$id)->select();

        foreach ($list as $k=>$v)
        {
            if ($v['item_type']=='goods')
            {
                $list[$k]['name'] = $v['name'].'/商品';
            }elseif ($v['item_type']=='project')
            {
                $list[$k]['name'] = $v['name'].'/项目';

            }
        }
        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('name', '套餐名称', 'text')
            ->addColumn('price', '项目价格', 'text')
            ->addColumn('number', '数量', 'text')
            ->setTableName('qt_data_package_item')// 指定数据表名
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('套餐列表')
            ->setRowList($list)// 设置表格数据
            ->fetch();
    }

    /**
     * 删除套餐里包含的项目或者商品
     * @param $id
     */
    public function delItem($id)
    {

        if ( ViperPackageItem::destroy($id))
        {
            $this->success('操作成功','index');
        }else{
            $this->error('删除失败');
        }
    }

}